<?php
namespace app\service;

use app\model\SendTemplateContentModel;
use share\exception\ApiException;
use share\service\BaseModelService;

class SendTemplateContentService extends BaseModelService{
    public static function getModel()
    {
        return new SendTemplateContentModel();
    }

    public static function addTemplateContent($item)
    {
        $origin = self::getByFilter(['no' => $item['no']]);
        if($origin){            
            throw  new ApiException("no:".$item['no']." already exists! please check");
        }
        return self::add($item);
    }

    public static function updateTemplateContent($id,$item)
    {
        $origin = self::getBase($id);
        if(!$origin){
            throw  new ApiException("data of id:{$id} is not exists! please check");
        }
        if($origin['no'] != $item['no']){
            $other = self::getByFilter(['no' => $item['no']]);
            if($other){
                throw  new ApiException("an other data of no:".$item['no']." already exists! please check");
            }
        }
        return  self::update($id,$item);
    }


    public static function setTemplateContent($param){
        $id =  $param['id'];
        unset($param['id']);
        if($id == 0){
            return self::addTemplateContent($param);
        }
        else{
            return self::updateTemplateContent($id,$param);
        }
    }

    public static function buildCondition($filter)
    {
        $res = [];
        if(isset($filter['no']) && !empty($filter['no'])){
            $res['no'] = ['like','%'.$filter['no'].'%'];
        }
        if(isset($filter['content']) && !empty($filter['content'])){
            $res['content'] = ['like','%'.$filter['content'].'%'];
        }   
        return $res;
    }
}